﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ThreadDemoOne
{
    internal class BaseSample
    {

        object uploadLocker = new object();
        int finishcount = 0;

        public void Start()
        {
            var videos = new List<VideoInfo>();
            for (int i = 0; i < 82; i++)
            {
                videos.Add(new VideoInfo() { Name = i.ToString() });
            }

            int threads = 1;
            if (videos.Count > 10)
            {
                threads = 5;
            }
            finishcount = 0;
            int count = videos.Count / threads;

            List<Thread> tasks = new List<Thread>();
            for (int i = 0; i < threads; i++)
            {
                List<VideoInfo> fileList = null;
                if (i == (threads - 1))
                {
                    fileList = videos.Skip(i * count).ToList();
                }
                else
                {
                    fileList = videos.Skip(i * count).Take(count).ToList();
                }
                Thread thread = new Thread(new ParameterizedThreadStart(UploadVideoList));
                thread.IsBackground = true;
                thread.Start(fileList);
                Console.WriteLine($"第{i}批视频正在导入\r\n");
                tasks.Add(thread);
            }
            Console.WriteLine($"上传云端开始：11");

            while (finishcount != threads)
            {
                Console.WriteLine($"上传云端中：{finishcount}");
                Thread.Sleep(100);
            }
            foreach (var item in tasks)
            {
                try
                {
                    item.Abort();
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"线程释放失败");
                }
            }

            Console.WriteLine($"上传云端结束：33");
        }

        private async void UploadVideoList(object? obj)
        {
            var videos = (List<VideoInfo>)obj;
            foreach (var item in videos)
            {
                Console.WriteLine($"上传云端：{item.Name} - {finishcount}");
                await Task.Delay(500);
            }
            lock (uploadLocker)
            {
                finishcount++;
                //Monitor.Pulse(uploadLocker); //完成，通知等待队列,告知已完，执行下一个。
            }
            Console.WriteLine($"线程结束：{Thread.CurrentThread.ManagedThreadId}");
        }
    }

    public class VideoInfo
    {
        public string Name { get; set; }

    }
}
